<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="initArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubArtVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" border style="width: 100%" stripe :header-cell-style="{ color: '#000' }">
        <el-table-column label="文章标题" prop="title">
          <template v-slot='scope'>
            <el-link @click="ArtPre(scope.row.id)">{{scope.row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发布时间">
          <template v-slot="row">{{ row.pub_date | dtformat }}</template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot='scope'>
            <el-button type="danger" @click="deleteArticle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      </el-card>

    <!-- 发表文章 -->
    <el-dialog title="发表文章" :visible.sync="pubArtVisible" :before-close="handleClose" fullscreen>
      <el-form ref="pubArtRef" :model="pubForm" :rules="pubFormRules" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!--Vue 富文本编辑器 -->
        <el-form-item label="文章内容:">
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>

        <el-form-item label="文章封面:">
          <div>
            <img :src="imgUrl" alt="" v-if="imgUrl" class="cover_img" />
            <img src="../../../assets/images/cover.jpg" alt="" v-else />
          </div>
          <input type="file" name="" style="display: none" ref="fileRef" @change="chooseImg" />
          <el-button type="text" @click="$refs.fileRef.click()">+ 选择封面</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="pubCategory('已发布')">发布</el-button>
          <el-button type="info" @click="pubCategory('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 文章预览 -->
    <el-dialog title="文章浏览" :visible.sync="ArtPreVisible" width="80%">
     <h1 class="title">{{artDetail.title}}</h1>

     <div class="info">
       <span>作者: {{artDetail.nickname}}</span>
       <span>发布时间: {{artDetail.pub_date| dtformat}}</span>
       <span>所属分类: {{artDetail.cate_name}}</span>
       <span>状态: {{artDetail.state}}</span>
     </div>

     <el-divider></el-divider>

     <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="">

     <div v-html="artDetail.content" class="detail-box"></div>

    </el-dialog>
  </div>
</template>

<script>
import { getCategoryAPI, addArticleAPI, getArticleAPI, deleteArticleAPI, getArtAPI } from '@/APl/article.js'
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubArtVisible: false,
      ArtPreVisible: false,
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      imgUrl: '',
      pubFormRules: {
        title: [
          { required: 'true', message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择活动区域', trigger: ['change', 'blur'] }]
      },
      cateList: [],
      artList: [],
      // 文章详情
      artDetail: {},
      total: 0
    }
  },
  created() {
    this.initCateList()
    this.initArtList()
  },
  methods: {
    handleClose(done) {
      this.$confirm('此操作将导致文章信息丢失,是否继续？', '提示', {
        type: 'warning'
      })
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    async initCateList() {
      const { data: res } = await getCategoryAPI()
      if (res.code === 0) {
        this.cateList = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    chooseImg(e) {
      if (e.target.files.length > 0) {
        const fileObj = e.target.files[0]
        this.imgUrl = URL.createObjectURL(fileObj)
        this.pubForm.cover_img = fileObj
      } else {
        this.pubForm.cover_img = ''
        this.imgUrl = ''
      }
    },
    pubCategory(s) {
      this.pubForm.state = s
      this.$refs.pubArtRef.validate(async valid => {
        if (valid) {
          if (this.pubForm.content === '') return this.$message.error('请填写内容')
          if (this.pubForm.cover_img === '') return this.$message.error('请添加图片')
          const fd = new FormData()
          for (const key in this.pubForm) {
            fd.append(key, this.pubForm[key])
          }
          const { data: res } = await addArticleAPI(fd)
          if (res.code === 0) {
            this.$message.success(res.message)
            this.pubArtVisible = false
            this.initArtList()
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },
    async initArtList() {
      const { data: res } = await getArticleAPI(this.q)
      // console.log(res.data)
      if (res.code === 0) {
        // this.$message.success(res.message)
        this.artList = res.data
        this.total = res.total
      }
    },
    handleSizeChange(strip) {
      this.q.pagesize = strip
      this.q.pagenum = 1
      this.initArtList()
    },
    handleCurrentChange(page) {
      this.q.pagenum = page
      this.initArtList()
    },
    resetList() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    deleteArticle(id) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await deleteArticleAPI(id)
          if (res.code === 0) {
            this.initArtList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {})
    },
    async ArtPre(id) {
      this.ArtPreVisible = true
      const { data: res } = await getArtAPI(id)
      if (res.code === 0) {
        this.artDetail = res.data
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor {
  height: 400px;
}
.cover_img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.el-link {
  color: rgb(98, 166, 221);
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}
.info{
  margin-bottom: 30px;
  span {
    margin-right: 15px;
  }
}
/deep/ .detail-box {
  img {
    width: 400px;
  }
}
</style>
